package com.caigou.modules.forum.ui.publish.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.CompoundButton
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.caigou.comm.base.bean.PrizeBallBean
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.container.BaseFragment
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.animals
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.forum.R
import com.caigou.modules.forum.adpter.ContestBallItem2Adapter
import com.caigou.modules.forum.adpter.ContestBallItemAdapter
import com.caigou.modules.forum.databinding.FragmentContestTeXiaoBinding
import com.caigou.modules.forum.viewmodel.PublishViewModel
import dagger.hilt.android.AndroidEntryPoint
import org.json.JSONArray
import org.json.JSONObject

/**
 * @author #Suyghur.
 * Created on 2021/12/26
 */
@AndroidEntryPoint
class TeXiaoFragment : BaseFragment() {

    private var _binding: FragmentContestTeXiaoBinding? = null
    private val binding get() = _binding!!

    private val publishViewModel: PublishViewModel by viewModels()

    private lateinit var sanXiaoAdapter: ContestBallItemAdapter
    private lateinit var erXiaoAdapter: ContestBallItemAdapter
    private lateinit var yiXiaoAdapter: ContestBallItemAdapter
    private lateinit var yiMaAdapter: ContestBallItem2Adapter

    private var sanXiaoCheckNum = 0
    private var erXiaoCheckNum = 0
    private var yiXiaoCheckNum = 0
    private var yiMaCheckNum = 0

    private var sanXiaoBalls = mutableListOf<String>()
    private var erXiaoBalls = mutableListOf<String>()
    private var yiXiaoBalls = mutableListOf<String>()
    private var yiMaBalls = mutableListOf<String>()

    private val prizeBalls = mutableListOf<PrizeBallBean>()


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentContestTeXiaoBinding.inflate(inflater, container, false)
        return _binding?.root
    }

    override fun initView() {
        handleSanXiaoView()
        handleErXiaoView()
        handleYiXiaoView()
        handleYiMaView()

        binding.contestTeXiaoBtnErXiaoAdd.setOnClickListener {
            if (sanXiaoCheckNum < 3) {
                showToast("请选择三肖")
                return@setOnClickListener
            }
            binding.contestTeXiaoCvErXiao.visibility = View.VISIBLE
            binding.contestTeXiaoBtnYiXiaoAdd.visibility = View.VISIBLE
            for (pos in 0..11) {
                sanXiaoAdapter.getViewByPosition(pos, R.id.item_publish_ball_cb)?.apply {
                    (this as CheckBox).isClickable = false
                }
            }
            erXiaoAdapter.setList(sanXiaoBalls)
            it.visibility = View.GONE
        }
        binding.contestTeXiaoIvErXiaoClear.setOnClickListener {
            binding.contestTeXiaoCvErXiao.visibility = View.GONE
            binding.contestTeXiaoBtnYiXiaoAdd.visibility = View.GONE
            binding.contestTeXiaoBtnErXiaoAdd.visibility = View.VISIBLE
            for (pos in 0..11) {
                sanXiaoAdapter.getViewByPosition(pos, R.id.item_publish_ball_cb)?.apply {
                    (this as CheckBox).isClickable = true
                }
            }
            for (pos in 0..2) {
                erXiaoAdapter.getViewByPosition(pos, R.id.item_publish_ball_cb)?.apply {
                    (this as CheckBox).isChecked = false
                }
            }
            erXiaoBalls.clear()
            erXiaoAdapter.setList(mutableListOf())
        }

        binding.contestTeXiaoBtnYiXiaoAdd.setOnClickListener {
            if (erXiaoCheckNum < 2) {
                showToast("请选择二肖")
                return@setOnClickListener
            }
            binding.contestTeXiaoIvErXiaoClear.visibility = View.GONE
            binding.contestTeXiaoBtnYiMaAdd.visibility = View.VISIBLE
            binding.contestTeXiaoCvYiXiao.visibility = View.VISIBLE
            for (pos in 0..2) {
                erXiaoAdapter.getViewByPosition(pos, R.id.item_publish_ball_cb)?.apply {
                    (this as CheckBox).isClickable = false
                }
            }
            yiXiaoAdapter.setList(erXiaoBalls)
            it.visibility = View.GONE
        }
        binding.contestTeXiaoIvYiXiaoClear.setOnClickListener {
            binding.contestTeXiaoIvErXiaoClear.visibility = View.VISIBLE
            binding.contestTeXiaoBtnYiMaAdd.visibility = View.GONE
            binding.contestTeXiaoBtnYiXiaoAdd.visibility = View.VISIBLE
            binding.contestTeXiaoCvYiXiao.visibility = View.GONE
            for (pos in 0..2) {
                erXiaoAdapter.getViewByPosition(pos, R.id.item_publish_ball_cb)?.apply {
                    (this as CheckBox).isClickable = true
                }
            }
            for (pos in 0..1) {
                yiXiaoAdapter.getViewByPosition(pos, R.id.item_publish_ball_cb)?.apply {
                    (this as CheckBox).isChecked = false
                }
            }
            yiXiaoBalls.clear()
            yiXiaoAdapter.setList(mutableListOf())
        }

        binding.contestTeXiaoBtnYiMaAdd.setOnClickListener {
            if (yiXiaoCheckNum < 1) {
                showToast("请选择一肖")
                return@setOnClickListener
            }
            binding.contestTeXiaoIvYiXiaoClear.visibility = View.GONE
            binding.contestTeXiaoCvYiMa.visibility = View.VISIBLE
            for (pos in 0..1) {
                yiXiaoAdapter.getViewByPosition(pos, R.id.item_publish_ball_cb)?.apply {
                    (this as CheckBox).isClickable = false
                }
            }

            val animalName = yiXiaoBalls[0]
            val tmp = prizeBalls.filter { ball -> ball.animalName == animalName }

            yiMaAdapter.setList(tmp)
            it.visibility = View.GONE
        }
        binding.contestTeXiaoIvYiMaClear.setOnClickListener {
            binding.contestTeXiaoIvYiXiaoClear.visibility = View.VISIBLE
            binding.contestTeXiaoCvYiMa.visibility = View.GONE
            binding.contestTeXiaoBtnYiMaAdd.visibility = View.VISIBLE
            for (pos in 0..1) {
                yiXiaoAdapter.getViewByPosition(pos, R.id.item_publish_ball_cb)?.apply {
                    (this as CheckBox).isClickable = true
                }
            }
            for (pos in 0 until yiMaAdapter.itemCount) {
                yiMaAdapter.getViewByPosition(pos, R.id.item_publish_ball2_cb)?.apply {
                    (this as CheckBox).isChecked = false
                }
            }
            yiMaBalls.clear()
            yiMaAdapter.setList(mutableListOf())
        }

        binding.contestTeXiaoBtnSubmit.setOnClickListener {
            val ob = JSONObject()
            val jsonArray = JSONArray()
            if (sanXiaoBalls.isNotEmpty()) {
                val jsonObject = JSONObject()

                val sanXiaoNums = mutableListOf<String>()
                val content = StringBuilder()
                sanXiaoBalls.forEach {
                    prizeBalls.forEach { ball ->
                        if (ball.animalName == it) {
                            sanXiaoNums.add(ball.number)
                        }
                    }
                }

                for (index in 0 until sanXiaoNums.size) {
                    if (index == 0) {
                        content.append("-")
                    }
                    content.append(sanXiaoNums[index]).append("-")
                }
                jsonObject.put("content", content)

                val contentDetail = binding.contestTeXiaoTvSanXiaoContent.text.toString().substringAfter("：")
                jsonObject.put("contentDetail", contentDetail)
                jsonObject.put("dareTypeId", 11)
                jsonArray.put(jsonObject)
            }

            if (erXiaoBalls.isNotEmpty()) {
                val jsonObject = JSONObject()

                val erXiaoNums = mutableListOf<String>()
                val content = StringBuilder()
                erXiaoBalls.forEach {
                    prizeBalls.forEach { ball ->
                        if (ball.animalName == it) {
                            erXiaoNums.add(ball.number)
                        }
                    }
                }

                for (index in 0 until erXiaoNums.size) {
                    if (index == 0) {
                        content.append("-")
                    }
                    content.append(erXiaoNums[index]).append("-")
                }
                jsonObject.put("content", content)

                val contentDetail = binding.contestTeXiaoTvErXiaoContent.text.toString().substringAfter("：")
                jsonObject.put("contentDetail", contentDetail)
                jsonObject.put("dareTypeId", 10)
                jsonArray.put(jsonObject)
            }

            if (yiXiaoBalls.isNotEmpty()) {
                val jsonObject = JSONObject()

                val yiXiaoNums = mutableListOf<String>()
                val content = StringBuilder()
                yiXiaoBalls.forEach {
                    prizeBalls.forEach { ball ->
                        if (ball.animalName == it) {
                            yiXiaoNums.add(ball.number)
                        }
                    }
                }

                for (index in 0 until yiXiaoNums.size) {
                    if (index == 0) {
                        content.append("-")
                    }
                    content.append(yiXiaoNums[index]).append("-")
                }
                jsonObject.put("content", content)

                val contentDetail = binding.contestTeXiaoTvYiXiaoContent.text.toString().substringAfter("：")
                jsonObject.put("contentDetail", contentDetail)
                jsonObject.put("dareTypeId", 9)
                jsonArray.put(jsonObject)
            }

            if (yiMaBalls.isNotEmpty()) {
                val jsonObject = JSONObject()

                val content = StringBuilder()

                for (index in 0 until yiMaBalls.size) {
                    if (index == 0) {
                        content.append("-")
                    }
                    content.append(yiMaBalls[index]).append("-")
                }
                jsonObject.put("content", content)

                val contentDetail = binding.contestTeXiaoTvYiMaContent.text.toString().substringAfter("：")
                jsonObject.put("contentDetail", contentDetail)
                jsonObject.put("dareTypeId", 8)
                jsonArray.put(jsonObject)
            }

            ob.put("dareContent", jsonArray.toString())
            ob.put("dareType", 1)
            LiveDataBus.get().with(BusKey.DARE_CONTENT_FILL, String::class.java).value = ob.toString()
            requireActivity().finish()
        }
    }

    override fun lazyLoad() {
        publishViewModel.getPrizeBallList()
    }

    override fun onBack() {
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(publishViewModel.prizeBallListLiveData, ::handleGetPrizeBallList)
    }

    private fun handleGetPrizeBallList(result: Resource<MutableList<PrizeBallBean>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                result.data?.apply {
                    prizeBalls.addAll(this)
                }
            }
        }
    }

    private fun handleSanXiaoView() {
        sanXiaoAdapter = ContestBallItemAdapter(animals) { buttonView, isChecked ->
            if (isChecked) {
                if (sanXiaoCheckNum < 3) {
                    sanXiaoCheckNum++
                    sanXiaoBalls.add(buttonView.text.toString())
                    changeSanXiaoContentTxt()
                } else {
                    showToast("最多选择3个")
                    buttonView.isChecked = false
                }
            } else {
                sanXiaoCheckNum--
                sanXiaoBalls.remove(buttonView.text.toString())
                changeSanXiaoContentTxt()
            }
        }

        binding.contestTeXiaoRecyclerViewSanXiao.run {
            layoutManager = GridLayoutManager(requireActivity(), 6)
            adapter = sanXiaoAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }
    }

    private fun handleErXiaoView() {
        erXiaoAdapter = ContestBallItemAdapter(mutableListOf()) { buttonView, isChecked ->
            if (isChecked) {
                if (erXiaoCheckNum < 2) {
                    erXiaoCheckNum++
                    erXiaoBalls.add(buttonView.text.toString())
                    changeErXiaoContentTxt()
                } else {
                    showToast("最多选择2个")
                    buttonView.isChecked = false
                }
            } else {
                erXiaoCheckNum--
                erXiaoBalls.remove(buttonView.text.toString())
                changeErXiaoContentTxt()
            }
        }

        binding.contestTeXiaoRecyclerViewErXiao.run {
            layoutManager = GridLayoutManager(requireActivity(), 6)
            adapter = erXiaoAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }
    }

    private fun handleYiXiaoView() {
        yiXiaoAdapter = ContestBallItemAdapter(mutableListOf()) { buttonView, isChecked ->
            if (isChecked) {
                if (yiXiaoCheckNum < 1) {
                    yiXiaoCheckNum++
                    yiXiaoBalls.add(buttonView.text.toString())
                    changeYiXiaoContentTxt()
                } else {
                    showToast("最多选择1个")
                    buttonView.isChecked = false
                }
            } else {
                yiXiaoCheckNum--
                yiXiaoBalls.remove(buttonView.text.toString())
                changeYiXiaoContentTxt()
            }
        }

        binding.contestTeXiaoRecyclerViewYiXiao.run {
            layoutManager = GridLayoutManager(requireActivity(), 6)
            adapter = yiXiaoAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }
    }

    private fun handleYiMaView() {
        yiMaAdapter = ContestBallItem2Adapter(mutableListOf(), object : ContestBallItem2Adapter.BallItemCallback {
            override fun onBallCheckedChange(buttonView: CompoundButton, isChecked: Boolean, item: PrizeBallBean) {
                if (isChecked) {
                    if (yiMaCheckNum < 1) {
                        yiMaCheckNum++
                        yiMaBalls.add(buttonView.text.toString())
                        changeYiMaContentTxt()
                    } else {
                        showToast("最多选择1个")
                        buttonView.isChecked = false
                    }
                } else {
                    yiMaCheckNum--
                    yiMaBalls.remove(buttonView.text.toString())
                    changeYiMaContentTxt()
                }
            }

        })

        binding.contestTeXiaoRecyclerViewYiMa.run {
            layoutManager = GridLayoutManager(requireActivity(), 7)
            adapter = yiMaAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }
    }


    private fun changeSanXiaoContentTxt() {
        if (sanXiaoBalls.isNullOrEmpty()) {
            return
        } else {
            val content: StringBuilder = StringBuilder("已选择：")
            for (index in 0 until sanXiaoBalls.size) {
                if (index == 0) {
                    content.append("-")
                }
                content.append(sanXiaoBalls[index]).append("-")
            }
            binding.contestTeXiaoTvSanXiaoContent.text = content
        }
    }


    private fun changeErXiaoContentTxt() {
        if (erXiaoBalls.isNullOrEmpty()) {
            return
        } else {
            val content: StringBuilder = StringBuilder("已选择：")
            for (index in 0 until erXiaoBalls.size) {
                if (index == 0) {
                    content.append("-")
                }
                content.append(erXiaoBalls[index]).append("-")
            }
            binding.contestTeXiaoTvErXiaoContent.text = content
        }
    }

    private fun changeYiXiaoContentTxt() {
        if (yiXiaoBalls.isNullOrEmpty()) {
            return
        } else {
            val content: StringBuilder = StringBuilder("已选择：")
            for (index in 0 until yiXiaoBalls.size) {
                if (index == 0) {
                    content.append("-")
                }
                content.append(yiXiaoBalls[index]).append("-")
            }
            binding.contestTeXiaoTvYiXiaoContent.text = content
        }
    }

    private fun changeYiMaContentTxt() {
        if (yiMaBalls.isNullOrEmpty()) {
            return
        } else {
            val content: StringBuilder = StringBuilder("已选择：")
            for (index in 0 until yiMaBalls.size) {
                if (index == 0) {
                    content.append("-")
                }
                content.append(yiMaBalls[index]).append("-")
            }
            binding.contestTeXiaoTvYiMaContent.text = content
        }
    }
}